/*
 * @Description:
 * @Author: charles
 * @Date: 2020-10-26 16:39:14
 * @LastEditors: charles
 * @LastEditTime: 2021-07-19 09:51:48
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [
  {
    path:"/",
    redirect:"/login",
  },
  {
    path: '/home',
    name: 'Home',
    meta: {
      scrollToTop: true
    },
    //匹配的页面
    component: () => import('../views/Home.vue'),
    //路由间的导航守卫
    // beforeEnter: (to, from, next) => {
    //   next()
    // }
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      scrollToTop: true
    },
    //匹配的页面
    component: () => import('../views/Login.vue')
  },
  {
    path: '/project',
    name: 'Project',
    meta: {
      scrollToTop: true
    },
    component: () => import('../views/Project.vue')
  },{
    path: '/apply',
    name: 'Apply',
    meta: {
      scrollToTop: true
    },
    component: () => import('../views/Apply.vue')
  },{
    path: '/applyQuery',
    name: 'ApplyQuery',
    meta: {
      scrollToTop: true
    },
    component: () => import('../views/ApplyQuery.vue')
  },{
    path: '/applySuccess',
    name: 'ApplySuccess',
    meta: {
      scrollToTop: true
    },
    component: () => import('../views/ApplySuccess.vue')
  }, {
    path: '/article',
    name: 'Article',
    meta: {
      scrollToTop: true
    },
    component: () => import('../views/Article.vue')
  }, 
   {
    path: '/contact',
    name: 'Contact',
    meta: {
      scrollToTop: true
    },
    component: () => import('../views/Contact.vue')
  }, 
  {
    path: '/list',
    name: 'List',
    meta: {
      scrollToTop: true
    },
    component: () => import('../views/List.vue')
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 使用 router.beforeEach 注册一个全局前置守卫，判断用户是否登陆
// to是要到的路由 from是要离开的路由 next是否允许进入目标路由的函数，即通过next控制能否到达目标路由 
//next必须调用
//还有beforeResolve（全局解析守卫)在导航被确认之前，所有组件内守卫和异步路由组件被解析后调用
//  afterEach全局后置钩子
// 组件的路由守卫beforeRouteEnter的next回调在生命周期mounted之后才会执行
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next();
  } else {
    let token = localStorage.getItem('Authorization');
    // console.log(token);
    if (token === null || token === '') {
      next('/login');
    } else {
      next();
    }
  }
});

export default router
